#!/bin/bash
# 前端部署脚本
# 该脚本仅部署已构建的前端，不执行构建步骤

# 设置颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 配置变量
DEPLOY_PATH="/home/pyapp/www/cardsys_test"
BACKUP_PATH="/home/pyapp/www/cardsys_test_backup_$(date +%Y%m%d_%H%M%S)"
BUILD_PATH="./frontend/dist"
SSH_PORT=6022  # 默认SSH端口为6022

echo -e "${YELLOW}===== 开始前端部署流程 =====${NC}"

# 检查是否在项目根目录
if [ ! -d "./frontend" ]; then
    echo -e "${RED}错误: 请在项目根目录运行此脚本${NC}"
    exit 1
fi

# 检查构建文件是否存在
if [ ! -d "$BUILD_PATH" ]; then
    echo -e "${RED}错误: 构建文件夹不存在 ($BUILD_PATH)${NC}"
    echo -e "${YELLOW}请先运行 ./frontend_build_local.sh 构建前端${NC}"
    exit 1
fi

# 提示输入服务器信息
echo -e "${YELLOW}请输入服务器用户名 (默认: pyapp):${NC}"
read -r server_user
server_user=${server_user:-pyapp}

echo -e "${YELLOW}请输入服务器地址:${NC}"
read -r server_host
if [ -z "$server_host" ]; then
    echo -e "${RED}错误: 服务器地址不能为空${NC}"
    exit 1
fi

echo -e "${YELLOW}请输入SSH端口 (默认: 6022):${NC}"
read -r input_port
SSH_PORT=${input_port:-$SSH_PORT}

# 检查服务器连接
echo -e "${YELLOW}正在检查服务器连接...${NC}"
ssh -p $SSH_PORT -q $server_user@$server_host exit
if [ $? -ne 0 ]; then
    echo -e "${RED}无法连接到服务器 $server_user@$server_host:$SSH_PORT${NC}"
    exit 1
fi

# 备份当前前端文件
echo -e "${YELLOW}[1/2] 备份当前前端文件...${NC}"
ssh -p $SSH_PORT $server_user@$server_host "if [ -d \"$DEPLOY_PATH\" ]; then mkdir -p $BACKUP_PATH && cp -r $DEPLOY_PATH/* $BACKUP_PATH/ && echo '已备份到 $BACKUP_PATH'; fi"

# 部署新的前端文件
echo -e "${YELLOW}[2/2] 正在部署新的前端文件...${NC}"
ssh -p $SSH_PORT $server_user@$server_host "mkdir -p $DEPLOY_PATH"
scp -P $SSH_PORT -r $BUILD_PATH/* $server_user@$server_host:$DEPLOY_PATH/

if [ $? -eq 0 ]; then
    echo -e "${GREEN}前端部署成功!${NC}"
    echo -e "${GREEN}访问地址: http://$server_host:8400${NC}"
else
    echo -e "${RED}前端部署失败${NC}"
    echo -e "${YELLOW}是否恢复备份? [y/N]${NC}"
    read -r restore_confirm
    if [[ "$restore_confirm" =~ ^[Yy]$ ]]; then
        ssh -p $SSH_PORT $server_user@$server_host "cp -r $BACKUP_PATH/* $DEPLOY_PATH/"
        echo -e "${GREEN}已恢复备份${NC}"
    fi
    exit 1
fi

echo -e "${GREEN}===== 前端部署流程完成 =====${NC}" 